<template>
  <div class="mod-config">
    <!--  用于过滤的表单  -->
    <normal-form ref='normalForm' :inline="true" :showNumber="searchFormShowNumber" :data-form="dataForm"
                 :showAll="false" :config="searchAttrs" :searchBtn="true" :submit-func="searchHandler">
      <!--  按钮组  -->
      <template v-slot:button>
        <el-button v-if="isAuth(saveAuthName)" type="primary" @click="addOrUpdateHandle(null,$event)" size="small"
                   icon="el-icon-edit">
          新增
        </el-button>
        <el-button v-if="isAuth(deleteAuthName)" type="danger" @click="deleteEntry()" size="small"
                   :disabled="dataListSelections.length <= 0">
          批量删除
        </el-button>
        <el-button v-if="isAuth(saveAuthName) && multiAdd" type="primary" @click="multiAddHandle()" size="small">
          批量新增
        </el-button>
        <el-button v-if="isAuth(saveAuthName) && deepMultiAdd" type="primary" @click="deepMultiAddHandle()" size="small">
          批量新增
        </el-button>
        <el-button v-if='templateDownloadApiName !== ""' type="success" size="small" @click="templateDownloadHandle()">
          模板下载
        </el-button>
        <el-upload v-if='importApiName !== ""' :show-file-list=false :action="importUrl" :on-success='getDataList'>
          <el-button size="small" type="primary">导入</el-button>
        </el-upload>
        <el-button type="success" size="small" v-if='exportApiName !== ""' @click="exportHandle()">导出</el-button>
        <el-button v-if='printFunc' size="small" type="warning" @click="printHandle">打印</el-button>
        <el-button v-if='isAuth(exportAuthName) &&exportPlantFunc' size="small" type="warning" :disabled="dataListSelections.length <= 0"
                   @click="plantFuncHandle">制作计划单
        </el-button>
        <el-button v-if='adviceNoteFunc' size="small" type="success" :disabled="dataListSelections.length <= 0"
                   @click="adviceNoteFuncHandle()">发货通知
        </el-button>
        <el-button v-if='isAuth(saveAuthName) &&multiUpdateStatusFunc' size="small" type="success" :disabled="dataListSelections.length <= 0"
                   @click="multiUpdateStatusFuncHandle">更新状态
        </el-button>
<!--        <el-button v-if='adviceNoteFunc' size="small" type="warning" :disabled="dataListSelections.length <= 0"-->
<!--                   @click="reorderFuncHandle">订单返单-->
<!--        </el-button>-->
        <!--  “头部”槽  -->
        <slot name="header"></slot>
      </template>
    </normal-form>
    <el-table ref="table" height="calc(100% - 150px)" :data="dataList" border v-loading="dataListLoading"
              :show-summary='sumInfo !== null'
              :summary-method="summariesFuncGet()" :span-method="spanFuncGet(requestData)"
              @selection-change="selectionChangeHandle"
              :highlight-current-row="highlightCurrentRow"
              :row-style="{height:0+'px'}"
              :cell-style="{padding:0+'px'}"
              :row-class-name="rowClassName"
              :header-cell-style="{ 'background-color': '#e5edfd' }"
              style="width: 100%;">
      <!--  单选框  -->
      <el-table-column type="selection" header-align="center" align="center" width="50"></el-table-column>
      <!--  序号  -->
      <el-table-column header-align="center" align="center" label="序号" width="70">
        <template slot-scope="scope">
          {{ (pageIndex - 1) * pageSize + scope.$index + 1 }}
        </template>


      </el-table-column>
      <template v-for="(key, index) in Object.keys(showAttrs)">
        <el-table-column v-if="isAuthForColumn(getDataConfigValue('showAuthName' ,key))" :prop="key"
                         header-align="center" align="center" :label="getDataConfigValue('label' ,key)" :key="index"
                         :width="getDataConfigValue('width' ,key)" show-overflow-tooltip>
          <template slot-scope="scope">
            <!--  图像显示  -->
            <template v-if="R.equals('image', getDataConfigValue('type' ,key))">
              <normal-img :url-attr="R.path(['row', key], scope)"></normal-img>
            </template>
<!--            -->
            <template v-else-if="R.equals('screenshotUpload', getDataConfigValue('type' ,key))">
              <normal-img :url-attr="R.path(['row', key], scope)"></normal-img>
            </template>

            <!--  日期显示  -->
            <template v-else-if="R.equals('date', getDataConfigValue('type' ,key))">
              {{ R.path(['row', key], scope)|formatDate }}
            </template>
            <!--  链接显示 -->
            <template v-else-if="R.equals('linkLabel', getDataConfigValue('type' ,key))">
              <link-label :routerName="getDataConfigValue('routerName' ,key)"
                          :searchObj="getLinkObj(getDataConfigValue('searchKey' ,key), key, getDataConfigValue('realKey' ,key) , scope)"
                          :label="R.path(['row', key], scope)"
              ></link-label>
            </template>
            <!--  单选项显示 -->
            <template v-else-if="R.equals('radio', getDataConfigValue('type' ,key))">
              <template v-for="item in getDataConfigValue('items' ,key)">
                <el-tag v-if="R.equals(item.value, R.path(['row', key], scope))"
                        size="small"
                        :type="item.tagType"
                        :Key="item.value"
                        :effect="getDataConfigValue('effect' ,key)"
                >{{ item.text }}
                </el-tag>
              </template>
            </template>
            <!--  标签显示 -->
            <template v-else-if="R.equals('tag', getDataConfigValue('type' ,key))">
              <el-tag :type="getDataConfigValue('tagType' ,key)"
                      :effect="getDataConfigValue('effect' ,key)"
              >{{ R.path(['row', key], scope) }}
              </el-tag>
            </template>

            <!--  范围显示 -->
            <template v-else-if="R.equals('tagRange', getDataConfigValue('type' ,key))">
              <el-tag v-if="R.path(['row', 'successRate'], scope)>=100" type="danger">{{ R.path(['row', key], scope) }} </el-tag>
              <el-tag v-else-if="R.path(['row', 'successRate'], scope)<65" type="warning">{{ R.path(['row', key], scope) }}</el-tag>
              <el-tag v-else-if="R.path(['row', 'successRate'], scope)>=65&&R.path(['row', 'successRate'], scope)<100" type="success">{{ R.path(['row', key], scope) }}</el-tag>
            </template>
            <!--  库存状态显示 -->
            <template v-else-if="R.equals('repertoryStatus', getDataConfigValue('type' ,key))">
              <el-tag
                v-if="isShortOfNumber(R.path(['row', getDataConfigValue('warningNumberAttr' ,key)], scope), R.path(['row', getDataConfigValue('residueWeightCount' ,key)], scope))"
                type="danger">
                缺货
              </el-tag>
              <el-tag v-else>充足</el-tag>
            </template>
            <!--  文件显示 -->
            <template v-else-if="R.equals('file', getDataConfigValue('type' ,key))">
              <el-button type="text"
                         @click="openOtherWindowHandle(`${imageUrl}${R.path(['row', key], scope)}?token=${token}`, R.path(['row', getDataConfigValue('showKey' ,key)], scope))">
                {{ R.path(['row', getDataConfigValue('showKey', key)], scope) }}
              </el-button>
            </template>
            <!--  带状态的文字显示 -->
            <template v-else-if="R.equals('labelWithStatus', getDataConfigValue('type' ,key))">
              <template v-for="item in getDataConfigValue('items' ,key)">
                <el-tag v-if="R.equals(item.value, R.path(['row', getDataConfigValue('statusAttr' ,key)], scope))"
                        size="mini"
                        :type="item.tagType"
                        :Key="item.value"
                        :effect="getDataConfigValue('effect' ,key)"
                >{{ item.text }}
                </el-tag>
                {{ R.path(['row', key], scope) }}
              </template>
            </template>
            <!--  价格显示-->
            <template v-else-if="R.equals('priceStatus', getDataConfigValue('type' ,key))">
              <el-tag v-if="isAuth(showPriceAuthName)">{{ R.path(['row', key], scope) }}</el-tag>
            </template>
<!--            百分比显示-->
            <template v-else-if="R.equals('progressStatus', getDataConfigValue('type' ,key))">

              <el-progress  v-if="R.path(['row', key], scope)<=30" status="warning" :text-inside="true" :stroke-width="24"  :percentage="R.path(['row', key], scope)"></el-progress>
              <el-progress  v-else-if="R.path(['row', key], scope)<=60&&R.path(['row', key], scope)>30"  :text-inside="true" :stroke-width="24"  :percentage="R.path(['row', key], scope)"></el-progress>
              <el-progress  v-else-if="R.path(['row', key], scope)<=78&&R.path(['row', key], scope)>60"  :text-inside="true" :stroke-width="24" color="#6f7ad3"  :percentage="R.path(['row', key], scope)"></el-progress>
              <el-progress  v-else  :text-inside="true" :stroke-width="24" status="success" :percentage="R.path(['row', key], scope)"></el-progress>
            </template>
            <!--  价格显示-->
            <template v-else-if="R.equals('priceStatus', getDataConfigValue('type' ,key))">
              <el-tag v-if="isAuth(showPriceAuthName)">{{ R.path(['row', key], scope) }}</el-tag>
            </template>

            <!--  数量 比较 -->
            <template v-else-if="R.equals('numberComparison', getDataConfigValue('type' ,key))">
              <el-tag
                v-if="(R.path(['row', getDataConfigValue('residueWeightCount' ,key)], scope)>R.path(['row', getDataConfigValue('warningNumberAttr' ,key)], scope))"
                type="danger">
                {{ Number(R.path(['row', getDataConfigValue('residueWeightCount' ,key)], scope)- R.path(['row', getDataConfigValue('warningNumberAttr' ,key)], scope)).toFixed(2)}}
              </el-tag>
              <el-tag v-else-if="(R.path(['row', getDataConfigValue('residueWeightCount' ,key)], scope)<R.path(['row', getDataConfigValue('warningNumberAttr' ,key)], scope))"
                      type="warning"
              >
                {{ Number(R.path(['row', getDataConfigValue('residueWeightCount' ,key)], scope)- R.path(['row', getDataConfigValue('warningNumberAttr' ,key)], scope)).toFixed(2)}}</el-tag>
              <el-tag v-else type="success"> {{ R.path(['row', getDataConfigValue('residueWeightCount' ,key)], scope)- R.path(['row', getDataConfigValue('warningNumberAttr' ,key)], scope)}} </el-tag>
            </template>

            <!-- 金额-->
            <template v-else-if="R.equals('money', getDataConfigValue('type' ,key))">
              <el-tag v-if="R.path(['row', getDataConfigValue('currencyType' ,key)], scope)==1||R.path(['row', getDataConfigValue('currencyType' ,key)], scope)==3" type="danger">¥{{ R.path(['row', key], scope)|formatMoney }}</el-tag>
              <el-tag v-else-if="R.path(['row', getDataConfigValue('currencyType' ,key)], scope)==2||R.path(['row', getDataConfigValue('currencyType' ,key)], scope)==4" type="success">${{ R.path(['row', key], scope)|formatMoney }}</el-tag>
              <el-tag v-else > {{ R.path(['row', key], scope)|formatMoney }} </el-tag>

            </template>

            <template v-else-if="R.equals('moneyContract', getDataConfigValue('type' ,key))">
              <el-tag v-if="R.path(['row', getDataConfigValue('currencyType' ,key)], scope)==0" type="danger">¥{{ R.path(['row', key], scope)|formatMoney }}</el-tag>
              <el-tag v-else-if="R.path(['row', getDataConfigValue('currencyType' ,key)], scope)==1" type="success">${{ R.path(['row', key], scope)|formatMoney }}</el-tag>
              <el-tag v-else > {{ R.path(['row', key], scope)|formatMoney }} </el-tag>

            </template>
            <!--  默认显示 -->
            <template v-else>
              {{ R.path(['row', key], scope) }}
            </template>
          </template>
        </el-table-column>
      </template>
      <!--  操作集合  -->
      <el-table-column fixed="right" header-align="center" align="center" :width="optionWidth" label="操作">-->
        <template slot-scope="scope">
          <!--  “尾部”槽  -->
<!--          <el-tooltip v-if="(isAuth(saveAuthName)&&!multiAdd)&&(!deepMultiAdd)" class="item" effect="dark" content="修改" placement="bottom"-->
<!--                      :hide-after="1800" :open-delay="800">-->
<!--            <el-button type="primary" icon="el-icon-edit" size="small"-->
<!--                       @click="addOrUpdateHandle(R.path(['row', primaryKey], scope))"></el-button>-->
<!--          </el-tooltip>-->
          <el-tooltip v-if="(isAuth(saveAuthName)&&showUpdateBtn)" class="item" effect="dark" content="修改" placement="bottom"
                      :hide-after="1800" :open-delay="800">
            <el-button type="primary" icon="el-icon-edit" size="small"
                       @click="addOrUpdateHandle(R.path(['row', primaryKey], scope))"></el-button>
          </el-tooltip>
          <el-tooltip v-if="isAuth(deleteAuthName)" class="item" effect="dark" content="删除" placement="bottom"
                      :hide-after="1800" :open-delay="800">
            <el-button type="danger" icon="el-icon-delete" size="small"
                       @click="deleteEntry(R.path(['row'], scope))"></el-button>
          </el-tooltip>
          <slot name="foot" v-bind:scope="scope"></slot>

        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      class="pagination-container"
      :current-page="pageIndex"
      :page-sizes="[20, 50, 100,200,1000]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper"
    ></el-pagination>
  </div>
</template>

<script>
import commonTableMixins from '@/utils/commonTableMixins'
import normalImg from '@/components/imgDisplayer'
import LinkLabel from '@/views/common/linkLabel'
import normalForm from '@/components/normalForm/form'
import {getUrl} from '@/utils/request'
import {btnBlur, downloadHandle, exportHandle, isAuth, isAuthForColumn, specialTypeCheck} from '@/utils'

export default {
  name: 'index',
  mixins: [commonTableMixins],
  components: {normalImg, LinkLabel, normalForm},
  computed: {
    importUrl() {
      return getUrl(this.importApiName, {token: this.$cookie.get('token')}, true)
    }
  },
  props: {
    searchFormShowNumber: {
      default: 5
    },
    deleteCheckFunc: {
      type: Function,
      default: () => {
        return () => true
      }
    },
    showUpdateBtn: {
      type: Boolean,
      default: true
    },
    multiAdd: {
      type: Boolean,
      default: false
    },
    deepMultiAdd: {
      type: Boolean,
      default: false
    },
    spanFuncGet: {
      type: Function,
      default: () => {
        return () => {
        }
      }
    },
    printFunc: {
      type: Function,
      default: null
    },
    /**
     * 需要“合计”的内容   {需要合计的列名 : request 根节点上的属性名}
     */
    sumInfo: {
      type: Object,
      default: null
    },
    /**
     * “操作”栏宽度
     */
    optionWidth: {
      type: Number,
      default: 150
    },
    /**
     * 需要作为可搜索项的属性的配置
     */
    searchAttrs: {
      type: Object,
      default: () => ({})
    },
    /**
     * 主键属性名
     */
    primaryKey: {
      type: String,
      default: ''
    },
    /**
     * 导入的API名称
     */
    importApiName: {
      type: String,
      default: ''
    },
    /**
     * 模板下载的API名称
     */
    templateDownloadApiName: {
      type: String,
      default: ''
    },
    /**
     * 展示数据的API名称
     */
    listApiName: {
      type: String,
      default: ''
    },
    /**
     * 删除数据的API名称
     */
    deleteApiName: {
      type: String,
      default: ''
    },
    /**
     * 导出数据的API名称
     */
    exportApiName: {
      type: String,
      default: ''
    },
    /**
     * 保存数据的权限名称
     */
    saveAuthName: {
      type: String,
      default: ''
    },
    /**
     * 删除数据的权限名称
     */
    deleteAuthName: {
      type: String,
      default: ''
    },
    /**
     * 导出计划生产订单 的权限名称
     */
    exportAuthName: {
      type: String,
      default: ''
    },
    /**
     * 需要在表格中显示的属性的配置
     */
    showAttrs: {
      required: true
    },
    /**
     * 显示价格
     * */
    showPriceAuthName: {
      type: String,
      default: ''
    },
    /**
     * 导出数据的API名称
     */
    exportPlantFunc: {
      type: Function,
      default: null
    },
    multiUpdateStatusFunc:{
      type: Function,
      default: null
    },
    /**
     * 活动通知
     */
    adviceNoteFunc: {
      type: Function,
      default: null
    },
    reorderFunc:{
      type: Function,
      default: null
    },
    highlightCurrentRow: {
      type: Boolean,
      default: false
    },
    rowClassName:{
      type: Function,
      default: null
    }
  },
  data() {
    return {
      dataForm: {},
      isAuth: isAuth,
      defaultConfig: {
        label: '省却值', // 标签内容
        type: '', // 显示类型
        width: '', // 宽度
        items: [], // radio 选项 {value: 0, text: '禁用', [tag 组件属性]},
        tagType: '', // tag type success，info，danger，warning
        effect: 'light' // tag 主题：dark、light 和 plain
      }
    }
  },
  methods: {
    deleteEntry(row) {
      let deleteItems = []
      let deleteId = null
      if (this.R.isNil(row)) {
        deleteItems = this.dataListSelections
      } else {
        deleteItems.push(row)
        deleteId = row[this.primaryKey]
      }
      if (!this.deleteCheckFunc(deleteItems)) {
        return
      }
      console.log(row, deleteId);
      this.deleteHandle(deleteId)
    },
    initDataForm() {
      if (Object.keys(this.searchAttrs).length > 0) {
        Object.keys(this.searchAttrs).forEach((key) => {
          this.$set(this.dataForm, key, '')
        })
      }
    },
    /**
     * 执行“在其他窗口打开”功能
     * @param url 下载地址
     */
    openOtherWindowHandle(url) {
      window.open(url)
    },
    /**
     * 获取属性配置项
     * @param attrName 属性名称
     * @param key 配置名称
     * @return *
     */
    getDataConfigValue(attrName, key) {
      const value = this.R.path([key, attrName], this.showAttrs)

      if (this.R.isNil(value)) {
        return this.R.prop(key, this.defaultConfig)
      }
      return value
    },
    /**
     * 获取“链接显示”的需要传递的参数对象
     * @param searchKey
     * @param key
     * @param scope
     * @param realKey
     * @return {*}
     */
    getLinkObj(searchKey, key, realKey, scope) {
      const obj = {}
      const tempValue = this.R.path(['row', realKey || key], scope)

      let autoCompleteValue = null

      if (realKey) {
        autoCompleteValue = this.R.path(['row', key], scope)
      }
      obj[searchKey] = {value: tempValue, autoCompleteValue}
      return obj
    },
    /**
     * 库存是否低于预警值
     * @param warningNumber 预警值
     * @param residueWeightCount 剩余库存
     * @returns {boolean}
     */
    isShortOfNumber(warningNumber, residueWeightCount) {
      return warningNumber > residueWeightCount
    },
    summariesFuncGet() {
      if (this.R.isNil(this.sumInfo)) {
        return
      }
      const sumIndexInfo = Object.keys(this.sumInfo).map(key => Object.keys(this.showAttrs).indexOf(key) + 2)

      return ({columns, data}) => {

        const sums = [];

        if (this.R.isNil(this.requestData)) {
          return sums
        }
        columns.forEach((column, index) => {
          if (index === 1) {
            sums[index] = '总计'
          } else {
            const tmpIndex = sumIndexInfo.indexOf(index)

            if (tmpIndex === -1) {
              sums[index] = ''
            } else {
              const values = data.map(this.R.propOr(0, Object.values(this.sumInfo)[tmpIndex]))

              sums[index] = values.reduce((prev, curr) => {
                const value = Number(curr)

                if (!isNaN(value)) {
                  return Math.round((prev + curr)*100)/100;
                }
                return prev
              }, 0)
            }
          }
        })
        this.$refs.table.doLayout()

        return sums
      }
    }
  },
  mounted() {
    this.initDataForm()
  }
}
</script>

<style scoped>
.el-form-item__content div {
  display: inline-block;
  margin: 0 10px;
}
</style>
<style >
.el-table .warning-row {
background: #f0c684;
}
.el-table .success-row {
background: rgba(138, 198, 103, 1);
}
.el-table .primary-row {
  background: #acd0f7;
}
.el-table .danger-row {
  background: #f5b0b0;
}
.el-table .special-row {
  background: #a5acd5;
}
.el-table .info-row {
  background: #f4f4f5;
}
.custom-theme .el-tag .el-tag--special {background-color: rgba(96, 8, 164, 0.1);border-color: rgba(73, 8, 164, 0.2);color:#7232dd}
</style>
